package com.ht.aems.fesmodel;

import org.apache.log4j.Logger;

/**
 * factory class for ProtocolHandler
 *
 * @author Dong Shufeng
 * @Date: 2006-12-2
 */
public class HandlerFactory {

    private static Logger log = Logger.getLogger(HandlerFactory.class);

    public static String[] getProtocolNames() {
        String[] protocolNames = new String[FesProperties.getProtocolNameList().size()];
        FesProperties.getProtocolNameList().toArray(protocolNames);
        return protocolNames;
    }

    public static String getProtocolName(Class c) {
        if (c == null)
            return null;
        return getProtocolName(c.getName());
    }

    public static String getProtocolName(String className) {
        if (className == null)
            return null;
        for (Integer key : FesProperties.getProtocolClassNames().keySet()) {
            if (FesProperties.getProtocolClassNames().get(key).equals(className))
                return FesProperties.getProtocolNames().get(key);
        }
        return null;
    }

    /**
     * @param deviceTypeId id of device type
     * @return 0: tcp server; 1: tcp client; 2: udp
     * <br>-1 if no tcp mode of this protocol connection mode is found.</br>
     */
    public static int getConnMode(Integer deviceTypeId) {
        if(deviceTypeId == null) return -1;
        if (FesProperties.getProtocolConnMode().get(deviceTypeId) == null)
            return -1;
        else
            return FesProperties.getProtocolConnMode().get(deviceTypeId);
    }

    public static ProtocolHandler createHandler(int deviceTypeId) {
        String className = FesProperties.getProtocolClassNames().get(deviceTypeId);
        if (className == null)
            return null;
        try {
            Object obj = Class.forName(className).newInstance();
            if (obj instanceof ProtocolHandler)
                return (ProtocolHandler) obj;
            else
                return null;
        } catch (Exception e) {
            log.warn(e);
            return null;
        }
    }
}
